package com.cms.controller;

import com.alibaba.fastjson.JSON;
import com.cms.common.JsonResult;
import com.cms.service.menu.MenuService;
import com.cms.service.menu.MenuServiceImpl;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.StringUtil;

import java.util.Date;

/**
 * Created by lichengming on 2017/6/14.
 */
public class HomeController extends Controller {

    MenuService menuService = new MenuServiceImpl();

    public void index() {

//        Record admin = getSessionAttr("admin");
//        String menuJson = JSON.toJSONString(menuService.getMenuListByUserId(admin.getLong("id")));
        String menuJson = JSON.toJSONString(menuService.getMenuListByUserId());
        setAttr("menuJson",menuJson);
        renderJsp("/home.jsp");
    }


    public void logout() {
        getSession().invalidate();
        renderJsp("/login.jsp");
    }

    public void toLogin() {
        getSession().invalidate();
        renderJsp("/login.jsp");
    }

    public void show() {
        renderJsp("/index.jsp");
    }



    public void login() {

        JsonResult result = new JsonResult();
        String userName = getPara("userName");
        String password = getPara("password");
        if (StringUtil.isEmpty(userName)) {
            renderJson(result.status("-1").show("用户名不能为空"));
            return;
        }

        if (StringUtil.isEmpty(password)) {
            renderJson(result.status("-2").show("密码不能为空"));
            return;
        }

        String querySQL = "select * from cms_admin where login_account = ? ";
        Record record = Db.findFirst(querySQL,userName);
        if (null == record) {
            renderJson(result.status("-3").show("用户名或密码不正确"));
            return;
        }

        String pass = record.getStr("password");
        if (!password.equals(pass)) {
            renderJson(result.status("-4").show("用户名或密码不正确"));
            return;
        }

        //更新
        record.set("last_login_time",new Date());
        Db.update("cms_admin",record);

        //登录通过
        setSessionAttr("admin",record);
        //一小时过期
        getSession().setMaxInactiveInterval(3600);
        renderJson(result.status("000"));
        return;
    }
}
